package cn.tpshion.devops.handle;

import cn.tpshion.devops.common.constant.RedisKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import javax.annotation.Resource;
import java.io.File;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@Component
@EnableScheduling
public class CleanHistoryHandle {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Value("${node.workspace}")
    private String workspace;

    @Value("${node.cleanSize}")
    private Long cleanSize;

    @Scheduled(cron = "0 0 3 * * ?")
    public void cleanHistory() {
        log.info("清理构建历史");
        // 查询所有项目
        Set<String> taskList = getTaskList();
        if(ObjectUtils.isEmpty(taskList)){
            return;
        }

        for (String taskId : taskList) {
            try {
                clean(taskId);
            }catch (Exception e){
                log.error("cleanHistory error:{}", e.getMessage(), e);
            }
        }
    }

    private Set<String> getTaskList(){
        HashOperations<String, String, String> hash = redisTemplate.opsForHash();
        return hash.keys(RedisKey.TASK_KEY);
    }

    private void clean(String taskId){
        HashOperations<String, String, String> hash = redisTemplate.opsForHash();
        Long size = hash.size(RedisKey.HISTORY + taskId);
        if(Objects.isNull(size) || size <= cleanSize){
            return;
        }

        List<Long> list = hash.keys(RedisKey.HISTORY + taskId).stream()
                .map(i -> Long.valueOf(i))
                .sorted(Long::compareTo)
                .limit(5)
                .collect(Collectors.toList());

        if(ObjectUtils.isEmpty(list)){
            return;
        }

        list.forEach(i -> {
            hash.delete(RedisKey.HISTORY + taskId, String.valueOf(i));
            try {
                StringBuilder builder = new StringBuilder();
                builder.append(workspace)
                        .append(File.separator)
                        .append(taskId)
                        .append(File.separator)
                        .append("log")
                        .append(File.separator)
                        .append(i + ".log");

                File file = new File(builder.toString());
                if(file.exists() && !file.isDirectory()){
                    file.delete();
                }
            }catch (Exception e){
                // ignore
            }
        });
    }
}
